// Copyright 2021 Chaos Mesh Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package v1alpha1

import (
	"fmt"
	"net/http"
	"net/url"
	"reflect"
	"strings"
	"time"

	"github.com/pkg/errors"
	"k8s.io/apimachinery/pkg/util/validation/field"
	logf "sigs.k8s.io/controller-runtime/pkg/log"

	"goproject/controllers/config"
	"goproject/pkg/chaosdclient"
)

var physicalMachineLog = logf.Log.WithName("physical-machine-resource")

const httpPrefix = "http://"
const httpsPrefix = "https://"

func generateChaosdDefaultAddress(address string) string {
	if config.ControllerCfg.ChaosdSecurityMode {
		// 应该以 https 开头
		if strings.HasPrefix(address, httpsPrefix) {
			return address
		}
		if strings.HasPrefix(address, httpPrefix) {
			// 实际 address 以 http 开头，但是 chaosdSecurityMode 为 true，需要替换为 https
			return strings.Replace(address, httpPrefix, httpsPrefix, 1)
		} else {
			// 实际 address 既不以 http 开头，也不以 https 开头，需要添加 https 前缀
			return fmt.Sprintf("%s%s", httpsPrefix, address)
		}
	} else {
		// 应该以 http 开头
		if strings.HasPrefix(address, httpPrefix) {
			return address
		}
		if strings.HasPrefix(address, httpsPrefix) {
			// 实际 address 以 https 开头，但是 chaosdSecurityMode 为 false，需要替换为 http
			return strings.Replace(address, httpsPrefix, httpPrefix, 1)
		} else {
			// 实际 address 既不以 http 开头，也不以 https 开头，需要添加 http 前缀
			return fmt.Sprintf("%s%s", httpPrefix, address)
		}
	}
}

// 请求 chaosd 健康检查街廓，间隔 100ms 最多重试 3 次，如果失败则返回错误
// FIXME 可能用时非常长，需要优化
func validateChaosdServer(address string) error {
	var ok bool
	for i := 0; i < 3; i++ {
		if i > 0 {
			time.Sleep(100 * time.Millisecond)
		}
		uri := fmt.Sprintf("%s/api/system/health", address)
		log.Info("HTTP request health", "address", address)
		statusCode, body, err := chaosdclient.DoHttpRequestChaosdServer(log, "GET", uri, nil)
		if err != nil {
			log.Error(err, "HTTP request health failed", "address", address)
			continue
		}
		if statusCode != http.StatusOK {
			err = errors.New("HTTP status is not OK")
			log.Error(err, "HTTP request health failed", "address", address, "statusCode", statusCode, "body", body)
			continue
		}
		ok = true
		break
	}
	if !ok {
		return errors.Errorf("the address '%s' is not reachable, chaosd server is not running, or chaosd server is not healthy", address)
	}
	return nil
}

func (in *PhysicalMachineSpec) Default(root interface{}, field *reflect.StructField) {
	if in == nil {
		return
	}

	physicalMachineLog.Info("default", "address", in.Address)
	in.Address = strings.TrimSpace(in.Address)
	if len(in.Address) == 0 {
		return
	}
	// add http or https prefix for address
	in.Address = generateChaosdDefaultAddress(in.Address)
}

// Validate 检查物理机定义格式
func (in *PhysicalMachineSpec) Validate(root interface{}, path *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	// make sure address is not empty
	if len(in.Address) == 0 {
		allErrs = append(allErrs,
			field.Invalid(path.Child("address"), in.Address, "the address is required"))
	}

	if _, err := url.ParseRequestURI(in.Address); err != nil {
		allErrs = append(allErrs,
			field.Invalid(path.Child("address"), in.Address, fmt.Sprintf("the address is invalid, %s", err)))
	}
	// 验证 chaosd server 是否运行
	err := validateChaosdServer(in.Address)
	if err != nil {
		allErrs = append(allErrs, field.Invalid(path.Child("address"), in.Address, err.Error()))
	}
	return allErrs
}
